//
//  BK_StorePay_VC.m
//  bestkeep
//
//  Created by TOPTEAM on 2017/3/31.
//  Copyright © 2017年 utouu. All rights reserved.
//

#import "BK_StorePay_VC.h"
#import "BK_SP_QR_Cell.h"
#import "BK_SP_Type_Cell.h"
#import <Masonry.h>
#import "BK_SP_ReminderView.h"
#import "BKUserUnitRequestAPI.h"
#import "BK_Store_BarCode_VC.h"
#import "Mediator+BKMy.h"
#import "BK_StorePay_Tool.h"
#import "BKODAliManager.h"
#import "BK_SP_Success_VC.h"
#import "BK_SP_Fail_VC.h"
#import "BK_SP_Help_VC.h"
#import "BK_StorePay_Model.h"
#import "UIView+ParentController.h"

@interface BK_StorePay_VC ()
<
UITableViewDelegate,
UITableViewDataSource,
BK_SP_Reminder_Delegate,
BK_SP_Type_Delegate,
WXApiManagerDelegate,
BKODAliManagerDelegate
>

@property(nonatomic, strong)ExceptionView * exceptionView;
@property(nonatomic, strong)NSMutableArray* marr_Section;
@property(nonatomic, strong)NSString      * str_Account_Balance;//

/*
 * 用来轮循   订单支付结果
 */
@property (nonatomic,strong) NSTimer *timer_Result;
@property (nonatomic,strong) BK_SP_ReminderView *view_Reminder;


@property (nonatomic,strong) BK_StorePay_Model  *model;
//获取当前屏幕的亮度:
@property (nonatomic,assign) CGFloat  currentLight;
@property (nonatomic,assign) float  interval;

@property (nonatomic,assign) float t;
@end

@implementation BK_StorePay_VC
- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self  setProperty];
    [self  createUI];
    [self  check_NetWork];
    [BKMyAction writeUTOUUPayStatus];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    
    if (_currentLight<=0.9) {
        _t=0.1;
        _interval=(0.9-_currentLight)/5.0;

//        [self delayMethod1];
    }
}


-(void)delayMethod1{
    [[UIScreen mainScreen] setBrightness: _currentLight+_interval];//0.9是自己设定认为比较合适的亮度值
    [self performSelector:@selector(delayMethod2) withObject:nil afterDelay:_t];
}
-(void)delayMethod2{
    [[UIScreen mainScreen] setBrightness: _currentLight+_interval*2];//0.9是自己设定认为比较合适的亮度值
    [self performSelector:@selector(delayMethod3) withObject:nil afterDelay:_t];
}
-(void)delayMethod3{
    [[UIScreen mainScreen] setBrightness: _currentLight+_interval*3];//0.9是自己设定认为比较合适的亮度值
    [self performSelector:@selector(delayMethod4) withObject:nil afterDelay:_t];
}
-(void)delayMethod4{
    [[UIScreen mainScreen] setBrightness: _currentLight+_interval*4];//0.9是自己设定认为比较合适的亮度值
    [self performSelector:@selector(delayMethod5) withObject:nil afterDelay:_t];
}
-(void)delayMethod5{

    [[UIScreen mainScreen] setBrightness: _currentLight+_interval*5];//0.9是自己设定认为比较合适的亮度值
}



-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    
    
    /*
     * 添加轮循查找
     */
    if (!_timer_Result) {
        if (_paymentCode) {
            [self appDidBecomeActive_RelayOutQR];
            [self add_timer_Result];
        }
    }
    
    
}



#pragma mark==================setProperty======================
-(void)setProperty{
    
    
    //注册通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(userDidTakeScreenshot:)
                                                 name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
    
    _model=[[BK_StorePay_Model alloc]init];
    
    _model.pay_type=10;//默认选择账户余额
    

    self.view .backgroundColor = [UIColor whiteColor];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"我要付款";
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.automaticallyAdjustsScrollViewInsets = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    _marr_Section=[[NSMutableArray alloc]init];
    
}

#pragma mark==================createUI======================
-(void)createUI{
    //获取当前屏幕的亮度:
    _currentLight = [[UIScreen mainScreen] brightness];
//    [[UIScreen mainScreen] setBrightness: 0.9];//0.9是自己设定认为比较合适的亮度值
    /*
     * 小店支付说明
     */
    UIImage *image = [[UIImage imageNamed:@"BK_PayStore_help"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    CGRect imageRect = CGRectMake(0.0, 0.0, 20, 20);
    [image drawInRect:imageRect];

    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStylePlain target:self action:@selector(BK_PayStore_help)];
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    
    [self.view addSubview:_tableView];
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
    }];

//    UIButton * btn=[[UIButton alloc]init];
//    btn.frame=CGRectMake(0, 0, 50, 50);
//    btn.backgroundColor=[UIColor cyanColor];
//    [btn addTarget:self action:@selector(Open_SP_ReminderView) forControlEvents:UIControlEventTouchUpInside];
//    [btn setTitle:@"测试" forState:UIControlStateNormal];
//    [self.view addSubview:btn];
    
    
}

#pragma mark==================checkNet======================
-(void)check_NetWork{
    RequestReachabilityStatus status = [RequestManager reachabilityStatus];
    switch (status) {
        case RequestReachabilityStatusReachableViaWiFi:
        case RequestReachabilityStatusReachableViaWWAN: {
            
            /*
             * 判断是否有支付秘钥   如果没有   获取
             */
            BKUserStatusInfo * userStatusInfo =[BKUserStatusInfo currentUser];
            if (userStatusInfo.userValidTime&&userStatusInfo.userSecretKey&&userStatusInfo.userPayWays&&[NSString stringWithFormat:@"%@",userStatusInfo.userValidTime].length>0&&[NSString stringWithFormat:@"%@",userStatusInfo.userSecretKey].length>0&&[NSString stringWithFormat:@"%@",userStatusInfo.userPayWays].length>0) {
                
                

                /*
                 * 获取小店付款数据
                 */
                [self get_StorePay_Data];
                
                
                /*
                 * 获取账户余额
                 */
                [self get_Account_Balance];
            }else{

                //获取用户支付密钥
                [[Mediator sharedInstance] BKMy_getUserSecret:^(id  _Nullable userSecretKey) {
                    if ([[userSecretKey objectForKey:@"success"] boolValue]) {

                        /*
                         * 获取小店付款数据
                         */
                        [self get_StorePay_Data];
                        
                        
                        /*
                         * 获取账户余额
                         */
                        [self get_Account_Balance];
                        
                    }else{
                        self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeRequestFailed];
                        ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeRequestFailed handler:^(ExceptionViewAction *action) {
                            [self.exceptionView dismiss];
                            self.exceptionView = nil;
                            [self check_NetWork];
                        }];
                        [self.exceptionView addAction:action];
                        [self.exceptionView showInView:self.view];
                    }
                }];
            }
        }
            break;
        default: {
            
            self.exceptionView = [ExceptionView exceptionViewWithType:ExceptionCodeTypeNoNetwork];
            ExceptionViewAction *action = [ExceptionViewAction actionWithType:ExceptionCodeTypeNoNetwork handler:^(ExceptionViewAction *action) {
                [self.exceptionView dismiss];
                self.exceptionView = nil;
                [self check_NetWork];
            }];
            [self.exceptionView addAction:action];
            [self.exceptionView showInView:self.view];
        }
            break;
    }
}
#pragma mark============================获取账户余额============================
-(void)get_Account_Balance{
    
    
    [BKIndicationView showInView:self.view];
    [BKUserUnitRequestAPI getUserAccountDetailWithBlock:^(id obj, NSError *error) {
        [BKIndicationView dismiss];
        if (obj) {
            

            
            
            NSDictionary * dict = obj;
            BOOL success = [[dict  objectForKey:@"success"] boolValue];
            if (success) {
                NSArray * dataArr = [[dict objectForKey:@"data"] objectForKey:@"account"];
                for (NSDictionary * temDict in dataArr) {
                    if ([temDict[@"account_type"] isEqualToString:@"002"]) {
                        NSLog(@"$$$$$%f",[temDict[@"account_balance"] floatValue]);
                        _str_Account_Balance = [NSString stringWithFormat:@"%@",temDict[@"account_balance"]];
                        if ([_str_Account_Balance floatValue]>0) {
                            
                        }else{
                            //余额为0
                            BK_SP_Type_Cell *cell = [_tableView  cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];

                            [cell SetNoMoney];
                            
                        }
                        
                        [_tableView reloadData];
                    }
                }
            }else{
                [HUD showMessage: dict[@"msg"]];
            }
        } else {
            
            if(!self.exceptionView && error) {
                
                if(!self.exceptionView && error) {
                    
                    ExceptionCodeType errorType = ExceptionCodeTypeRequestFailed;
                    if (error.code == -1009) {
                        errorType = ExceptionCodeTypeNoNetwork;
                    }else if (error.code == -1001){
                        errorType = ExceptionCodeTypeRequestFailed;
                    }else if (error.code == 502 || error.code == 404){
                        errorType = ExceptionCodeTypeServerError;
                    }else{
                        errorType = ExceptionCodeTypeFailedToLoad;
                    }
                    
                    self.exceptionView = [ExceptionView exceptionViewWithType:errorType];
                    ExceptionViewAction *retryAction = [ExceptionViewAction actionWithType:errorType handler:^(ExceptionViewAction *action) {
                        [self.exceptionView dismiss];
                        self.exceptionView = nil;
                        [self get_Account_Balance];
                    }];
                    [self.exceptionView addAction:retryAction];
                    [self.exceptionView showInView:self.view];
                    
                }
            }
        }
    }];

}




#pragma mark============================获取小店订单支付信息============================
-(void)get_StorePay_Data{
    
    NSMutableArray * marr_Cells=[[NSMutableArray alloc]init];
    
    
    CellModel* model0 =[[CellModel alloc]init];
    model0.reuseIdentifier = NSStringFromClass([BK_SP_QR_Cell class]);
    model0.className=NSStringFromClass([BK_SP_QR_Cell class]);
    model0.height = [BK_SP_QR_Cell computeHeight:nil];
    model0.selectionStyle=UITableViewCellSelectionStyleNone;
    model0.accessoryType=UITableViewCellAccessoryNone;
    [marr_Cells addObject:model0];
    
    
    CellModel* model1 =[[CellModel alloc]init];
    model1.reuseIdentifier = NSStringFromClass([BK_SP_Type_Cell class]);
    model1.className=NSStringFromClass([BK_SP_Type_Cell class]);
    model1.height = [BK_SP_Type_Cell computeHeight:nil];
    model1.selectionStyle=UITableViewCellSelectionStyleNone;
    model1.accessoryType=UITableViewCellAccessoryNone;
    [marr_Cells addObject:model1];
    
    
    SectionModel *model_Section=[SectionModel sectionModelWithTitle:@"" cells:marr_Cells];
    model_Section.headerhHeight=0.0001;
    model_Section.footerHeight=0.0001;
    [_marr_Section addObject:model_Section];
    
    
    [_tableView reloadData];
    /*
     * 添加轮循查找
     */
    [self add_timer_Result];
    
}

#pragma mark tableView 代理相关
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _marr_Section.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.cells.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    SectionModel *sm = _marr_Section[section];
    return sm.footerHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    return cm.height;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    SectionModel *sm = _marr_Section[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if (!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.selectionStyle = cm.selectionStyle;
    
    if ([cm.className isEqualToString:NSStringFromClass([BK_SP_QR_Cell class])]) {
        BK_SP_QR_Cell *ex_cell=(BK_SP_QR_Cell *)cell;
        ex_cell.type_pay=_model.pay_type;
        [ex_cell relayOut_QRCode];
    }
    
    if ([cm.className isEqualToString:NSStringFromClass([BK_SP_Type_Cell class])]) {
        BK_SP_Type_Cell *ex_cell=(BK_SP_Type_Cell *)cell;
        ex_cell.delegate=self;
        [ex_cell relayOutUIWithMoney:_str_Account_Balance];
    }
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    

    
}


#pragma mark============================轮循接口============================
-(void)get_Pay_Result{
    
    
    if (_paymentCode) {
       NSLog(@"轮询付款码：-》%@",_paymentCode);
    }else{
      
    }
    
    NSDictionary *paramDic =  @{@"paymentCode" : _paymentCode};
    NSString *const BKStorePayInfo_URL      = @"pay/getStorePayInfo";

    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:kOrderURL(BKStorePayInfo_URL) parameters:paramDic success:^(id  _Nullable responseObject){
        
        BOOL success = [responseObject[@"success"] boolValue];

        if (!success) {
//            kOrderPromptMsg(responseObject[@"msg"]);

        }else{

            if (responseObject[@"data"]) {
                
                /*
                 * "支付状态 0：未支付，1:支付成功，2：支付失败",
                 */
                if ([[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_status"]] integerValue]==1) {
                    /*
                     * 1:支付成功
                     */
                    //结束轮循
                    [self Close_timer_Result];

                    /*
                     * 支付成功---》跳转成功页面
                     */
                    _model.pay_amount=[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_amount"]] ;
                    _model.order_no=[NSString stringWithFormat:@"%@",responseObject[@"data"][@"order_no"]] ;
                    _model.pay_type=[[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_way"]] integerValue] ;
                    [self get_Account_Balance];
                    BK_SP_Success_VC *vc=[[BK_SP_Success_VC alloc]init];
                    vc.model=_model;
                    [self.navigationController pushViewController:vc animated:YES];
                    
                }else if([[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_status"]] integerValue]==0){
                    /*
                     *  0：未支付
                     */
                    if ([[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_way"]] integerValue]==20) {
                        //结束轮循
                        [self Close_timer_Result];
                        //结果二：选择支付宝
                        _model.order_no=responseObject[@"data"][@"order_no"];
                        _model.pay_amount=responseObject[@"data"][@"pay_amount"];
                        _model.pay_type=[[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_way"]] integerValue] ;
                        

                        [self transPayOrder_no:responseObject[@"data"][@"pay_info"]];
                        
                    }else if([[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_way"]] integerValue]==30){
                        
                        
                        //结束轮循
                        [self Close_timer_Result];
                        //结果三：选择微信
                        
                        _model.order_no=responseObject[@"data"][@"order_no"];
                        _model.pay_amount=responseObject[@"data"][@"pay_amount"];
                        _model.pay_type=[[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_way"]] integerValue] ;
                        
                        
                        [self transPayInfoToWeiXin:responseObject[@"data"][@"pay_info"]];
                        
                    }
                }else if([[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_status"]] integerValue]==2){
                    /*
                     * 支付失败
                     */
 
                    //余额支付
                    if ([[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_way"]] integerValue]==10) {
                        

                        if ([[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_amount"]] floatValue]>[_str_Account_Balance floatValue]) {
                            
                            _model.order_no=responseObject[@"data"][@"order_no"];
                            _model.pay_amount=responseObject[@"data"][@"pay_amount"];
                            _model.pay_type=[[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_way"]] integerValue] ;
                            
                            //结束轮循
                            [self Close_timer_Result];
                            /*
                             * 结果一： 账户余额不够-》弹出提示  余额不足
                             */
                            [self Open_SP_ReminderView];

                        }
                    }else if([[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_way"]] integerValue]==20){
                        kOrderPromptMsg(responseObject[@"msg"]);
                    }else if([[NSString stringWithFormat:@"%@",responseObject[@"data"][@"pay_way"]] integerValue]==30){
                        kOrderPromptMsg(responseObject[@"msg"]);
                    }
                    
                }
            }
        }
        
        
    }failure:^(id  _Nullable responseObject, NSError * _Nullable error){


        
        if ([RequestManager reachabilityStatus] == RequestReachabilityStatusUnknown || [RequestManager reachabilityStatus] == RequestReachabilityStatusNotReachable) {
            
        }else{
            NSString *errorMsg;
            if (error.code == -1001) {
                errorMsg = @"请求超时";
            }else if(error.code == 502){
                errorMsg = @"服务器开小差了，请稍后再试！";
            }else{
                errorMsg = @"请求失败";
            }
//            kOrderPromptMsg(errorMsg);
        }


    }];
  
    
}



#pragma mark-微信支付
- (void)transPayInfoToWeiXin:(NSString *)pay_info {
    _model.pay_info=pay_info;
    if (![WXApi isWXAppInstalled]) {
        [HUD showMessage:@"您还没有安装微信客户端"];
    }
    NSDictionary *payInfoDic = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:[pay_info UTF8String] length:pay_info.length] options:NSJSONReadingMutableLeaves error:nil];
    PayReq *req = [[PayReq alloc] init];
    req.nonceStr = payInfoDic[@"noncestr"];
    req.package = payInfoDic[@"package"];
    req.partnerId = payInfoDic[@"partnerid"];
    req.prepayId = payInfoDic[@"prepayid"];
    req.sign = payInfoDic[@"sign"];
    req.timeStamp = (UInt32)[payInfoDic[@"timestamp"] intValue];
    
    [WXApi registerApp:@"wx2c7367321c4ecab5"];
    //调微信支付
    [WXApiManager sharedManager].delegate = self;
    [WXApi sendReq:req];
}
#pragma mark-微信支付 回调
- (void)managerDidRecvPayResponse:(PayResp *)response {

    if (response.errCode == 0) {//支付成功
        /*
         * 支付成功---》跳转成功页面
         */
        BK_SP_Success_VC *vc=[[BK_SP_Success_VC alloc]init];
        vc.model=_model;
        [self.navigationController pushViewController:vc animated:YES];
        
    } else {
        /*
         * 支付失败---》跳转失败页面
         */
        BK_SP_Fail_VC  *vc =[[BK_SP_Fail_VC alloc]init];
        vc.model=_model;
        [self.navigationController pushViewController:vc animated:YES];

    }
}


#pragma mark-支付宝支付；
- (void)transPayOrder_no:(NSString *)pay_info {
    _model.pay_info=pay_info;
    [BKODAliManager manager].delegate = self;
    [[BKODAliManager manager] payRequestOrderString:pay_info];
}

#pragma mark-支付宝支付回调
- (void)ODWAliManagerDidRecvPayResult:(NSDictionary *)resultDic {

    if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {//支付成功
        /*
         * 支付成功---》跳转成功页面
         */
        BK_SP_Success_VC *vc=[[BK_SP_Success_VC alloc]init];
        vc.model=_model;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        
        /*
         * 支付失败---》跳转失败页面
         */
        BK_SP_Fail_VC  *vc =[[BK_SP_Fail_VC alloc]init];
        vc.model=_model;
        vc.block =^(NSInteger t){//回调

        };
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}


#pragma mark-打开付款提示
-(void)Open_SP_ReminderView{
    
    if (!_view_Reminder) {
        
        CGRect frame = self.view.bounds;
        frame.size.height = ScreenHeight;
        _view_Reminder = [[BK_SP_ReminderView alloc] initWithFrame:frame];
        _view_Reminder.delegate=self;
        [_view_Reminder relayOut_CountMoney:_str_Account_Balance];
        [_view_Reminder relayOut_NeedMoney:_model.pay_amount];
        [[self lastWindow] addSubview:_view_Reminder];
        [[self lastWindow] bringSubviewToFront:_view_Reminder];
        [_view_Reminder Btn_SelectedWithTag:_model.pay_type+1000];
    }
    _view_Reminder.view_detail.frame = CGRectMake(0, ScreenHeight, ScreenWidth, 745/2.0 );
    [UIView animateWithDuration:0.3 animations:^{
        _view_Reminder.view_detail.frame = CGRectMake(0, ScreenHeight -745/2.0 , ScreenWidth, 745/2.0);
    }];
}

- (void)clickCancelButton {
    [UIView animateWithDuration:0.1 animations:^{
        _view_Reminder.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.3 animations:^{
            CGRect frame = self.view.bounds;
            frame.size.height = ScreenHeight;
            frame.origin.y = ScreenHeight;
            _view_Reminder.frame = frame;
        } completion:^(BOOL finished) {
            [_view_Reminder removeFromSuperview];
            _view_Reminder = nil;
            [self add_timer_Result];
        }];
    }];
    
}
#pragma BK_SP_Reminder_Delegate
#pragma mark-点击退出
-(void)BK_SP_Reminder_clicked_Cancle{
    [self clickCancelButton];
    
    _model.pay_type=10;
    
    
    /*
     * 进入支付失败页面
     */
    BK_SP_Fail_VC  *vc =[[BK_SP_Fail_VC alloc]init];
    vc.model=_model;
    vc.block =^(NSInteger t){//回调
        
    };
    [self.navigationController pushViewController:vc animated:YES];
    
    
}
#pragma mark-选择付款方式
- (void)BK_SP_Reminder_clicked_Type:(NSInteger)t{
    _model.pay_type=t;
    NSLog(@"Reminder->%ld",(long)t);
    
    BK_SP_Type_Cell *cell = [_tableView  cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    [cell Btn_SelectedWithTag:t+10000];
    
    /*
     * 更新付款码
     */
    BK_SP_QR_Cell *cell_QR = [_tableView  cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [cell_QR relayOut_QRType:t];
    
    if (t==20) {
        /*
         * 支付宝付款
         */

        
    }else if(t==30){
        /*
         * 微信付款
         */
        
    }
    
    [self clickCancelButton];
    
    
}
#pragma BK_SP_Type_Delegate
#pragma mark-选择付款方式
- (void)BK_SP_Type_clicked:(NSInteger)t{
    _model.pay_type=t;
    /*
     * 更新付款码   
     */
    BK_SP_QR_Cell *cell = [_tableView  cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    [cell relayOut_QRType:t];

    NSLog(@"uuuuuuuuu->%ld",(long)t);
}


- (UIWindow *)lastWindow {
    
    return [UIApplication sharedApplication].keyWindow;
}


#pragma mark============================开启轮循查找结果============================
-(void)add_timer_Result{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(get_Pay_Result) userInfo:nil repeats:YES];
    _timer_Result = timer;
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
#pragma mark============================结束轮询============================
-(void)Close_timer_Result{
    [_timer_Result invalidate];
    _timer_Result = nil;
}
-(void)dealloc{
    [self Close_timer_Result];
    [_view_Reminder removeFromSuperview];
    _view_Reminder.delegate=nil;
    _view_Reminder = nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}
-(void)appDidBecomeActive_RelayOutQR{
    /*
     * 更新付款码
     */
    if (_model.pay_type) {
        BK_SP_QR_Cell *cell = [_tableView  cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        [cell relayOut_QRType:_model.pay_type];
    }
    
}
#pragma 小店支付帮助页面
-(void)BK_PayStore_help{
    BK_SP_Help_VC * vc =[[BK_SP_Help_VC alloc]init];

    vc.urlString=@"http://cdn.bestkeep.cn/ui/mobile/html/martOrderList.html";
//    vc.titleStr=@"";
    vc.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    if (_currentLight>=0) {
        [[UIScreen mainScreen] setBrightness: _currentLight];//0.9是自己设定认为比较合适的亮度值
    }
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self Close_timer_Result];
    [_view_Reminder removeFromSuperview];
    _view_Reminder.delegate=nil;
    _view_Reminder = nil;
     BK_SP_QR_Cell *cell = [_tableView  cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    if (cell) {

        [cell.timer invalidate];
        cell.timer = nil;
    }
}

/*
 * 监听截屏:执行操作, 也就是实现上面通知对应的响应函数 －－ userDidTakeScreenshot
 */

//截屏响应
- (void)userDidTakeScreenshot:(NSNotification *)notification
{
    NSLog(@"检测到截屏");
    

    if ([[UIView BKcurrentViewController] isKindOfClass:[BK_StorePay_VC class]]) {
        kOrderPromptMsg(@"该功能用于向商家付款时出示使用，请不要将付款码及数字发送给他人");
    }
    
    

}

-(void)Img_imageWithScreenshot{
        //人为截屏, 模拟用户截屏行为, 获取所截图片
        UIImage *image_ = [self imageWithScreenshot];
    
        //添加显示
        UIImageView *imgvPhoto = [[UIImageView alloc]initWithImage:image_];
        imgvPhoto.frame = CGRectMake(self.view.frame.size.width/2, self.view.frame.size.height/2, self.view.frame.size.width/2, self.view.frame.size.height/2);
    
        //添加边框
        CALayer * layer = [imgvPhoto layer];
        layer.borderColor = [
                             [UIColor whiteColor] CGColor];
        layer.borderWidth = 5.0f;
        //添加四个边阴影
        imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;
        imgvPhoto.layer.shadowOffset = CGSizeMake(0, 0);
        imgvPhoto.layer.shadowOpacity = 0.5;
        imgvPhoto.layer.shadowRadius = 10.0;
        //添加两个边阴影
        imgvPhoto.layer.shadowColor = [UIColor blackColor].CGColor;
        imgvPhoto.layer.shadowOffset = CGSizeMake(4, 4);
        imgvPhoto.layer.shadowOpacity = 0.5;
        imgvPhoto.layer.shadowRadius = 2.0;
        
        [[self lastWindow] addSubview:imgvPhoto];
}
/**
 *  截取当前屏幕
 *
 *  @return NSData *
 */
- (NSData *)dataWithScreenshotInPNGFormat
{
    CGSize imageSize = CGSizeZero;
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationIsPortrait(orientation))
        imageSize = [UIScreen mainScreen].bounds.size;
    else
        imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
    
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    for (UIWindow *window in [[UIApplication sharedApplication] windows])
    {
        CGContextSaveGState(context);
        CGContextTranslateCTM(context, window.center.x, window.center.y);
        CGContextConcatCTM(context, window.transform);
        CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
        if (orientation == UIInterfaceOrientationLandscapeLeft)
        {
            CGContextRotateCTM(context, M_PI_2);
            CGContextTranslateCTM(context, 0, -imageSize.width);
        }
        else if (orientation == UIInterfaceOrientationLandscapeRight)
        {
            CGContextRotateCTM(context, -M_PI_2);
            CGContextTranslateCTM(context, -imageSize.height, 0);
        } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
            CGContextRotateCTM(context, M_PI);
            CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
        }
        if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
        {
            [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
        }
        else
        {
            [window.layer renderInContext:context];
        }
        CGContextRestoreGState(context);
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return UIImagePNGRepresentation(image);
}

/**
 *  返回截取到的图片
 *
 *  @return UIImage *
 */
- (UIImage *)imageWithScreenshot
{
    NSData *imageData = [self dataWithScreenshotInPNGFormat];
    return [UIImage imageWithData:imageData];
}


@end





















































